const md5 = require('./md5')
const qs = require('./qs.js')
// 获取 App 实例
const App = getApp();

// 请求前缀
const BASE_URL = 'https://platform.easys.co';  // 线上环境

// 小程序
// const name = 'vend';   // Faceplay
const name = "guobo";     // 艺数星球

// 支付 appid
// const appid = 'wx53390cf0f4cc121a' // Faceplay
const appid = 'wxbe4b281e070bed97' // 艺数星球

// 定义一个函数来获取 sid
function getSid() {
  const app = getApp();
  return app.globalData.sid;
}

// 定义一个函数来获取 openid
function getOpenid() {
  return wx.getStorageSync('openid');
}

const _JSON = 'application/json;charset:UTF-8';
const _FORM = "application/x-www-form-urlencoded;charset:UTF-8";
const _FORM2 = "application/x-www-form-urlencoded";

const http = {
  // planet_id,
  BASE_URL,
  globalData: {
    planet_id: 981,
    // planet_id:956,
    needBeginLogin: true,
    exeQueue: true,
    promiseQueue: []
  },
  /**get 请求 */
  get: function (url, data, isToken = true) {
    const openid = getOpenid();
    const sid = getSid();
    const newData = { ...data, openid, sid };
    const requestUrl = this.getUrl(url, newData);
    let requestObj = {
      url: requestUrl,
      method: 'GET',
      data
    }
    return this.promiseRequest(requestObj);
  },

  /**post 请求 */
  post: function (url, data, isToken = true, form) {
    const openid = getOpenid();
    const sid = getSid();
    const newData = { ...data, openid, sid };
    let requestObj = {
      url,
      method: 'POST',
      data: newData,
      contentType: form
    }
    return this.promiseRequest(requestObj);
  },

  // url 加上需带参数
  getUrl: function (url, params) {
    if (url.match(/^http/)) {
      return url;
    }
    url = this.appendParams(url, params);
    return url.indexOf('/') === 0 ? BASE_URL + url : BASE_URL + '/' + url;
  },
  promiseRequest: function (requestObj) {
    let _this = this;
    return new Promise((resolve, reject) => {
      wx.getStorage({
        key: 'openid',
      }).then(res => {
        console.log(res)
        let requestUrl = _this.getUrl(requestObj.url, { openid: res.data });
        getRequst(requestUrl);
      }).catch((res => {
        let requestUrl = _this.getUrl(requestObj.url, { openid: '' });
        getRequst(requestUrl);
      }));

      var getRequst = (requestUrl) => {

        console.log(requestObj.contentType === 'json' ? _JSON : requestObj.contentType === 'form' ? _FORM2 : _FORM,)
        // 网络请求
        wx.request({
          url: requestUrl,
          data: requestObj.data,
          method: requestObj.method,
          header: {
            'content-type': 'application/json'
            // 'Content-Type': requestObj.contentType === 'json' ? _JSON : requestObj.contentType === 'form' ? _FORM2 : _FORM,
          },

          success: (res) => {
            // debugger
            let promiseQueue = _this.globalData.promiseQueue;
            if (res.statusCode == 500 || res.statusCode == 404) {
              wx.showModal({
                title: '提示',
                content: '服务器繁忙，请重试',
                success: function (res) {
                  if (res.confirm) {
                  }
                }
              })
            } else if (res.data.code == 200) {
              if (requestObj.resolve) { // 如果是 promise 队列中的请求。
                requestObj.resolve(res.data);
                let promiseQueueItem = promiseQueue.shift();
                if (_this.globalData.exeQueue) { // 如果队列可执行则循环队列，保持队列只被循环一次。
                  _this.globalData.exeQueue = false; // 防止被多次循环。
                  while (promiseQueueItem) {
                    _this.promiseRequest(promiseQueueItem);
                    promiseQueueItem = promiseQueue.shift();
                  }
                  if (!promiseQueueItem) {
                    _this.globalData.exeQueue = true;
                    _this.globalData.needBeginLogin = true;
                  }
                }
              } else {
                resolve(res.data);
              }
            }
            else if (res.data.code == 4001 || res.data.code == 4002) {
              _this.clearStorage()
              // 登录过期 刷新登录
              requestObj.resolve = resolve;
              promiseQueue.push(requestObj); // 请求失败了，把该请求放到 promise 队列，等待更新 token 后重新调用。
              if (!_this.globalData.needBeginLogin) { // 如果不需要重新登录
                return;
              }
              // 防止重复调用 login。
              _this.globalData.needBeginLogin = false;
              _this.login(() => { // 获取完 token 以后执行回调
                // 重新登陆以后调用一次队列中的 promise；并设置队列为可循环状态。
                let promiseQueueItem = promiseQueue.shift();
                if (promiseQueueItem) {
                  _this.globalData.exeQueue = true;
                  _this.promiseRequest(promiseQueueItem);
                }
              })

            } else {
              resolve(res.data)
            }
          },
          fail: (err) => {
            wx.hideLoading()
            // wx.showToast({
            //   title: "网络超时",
            //   icon: "error",
            //   duration: 3000
            // })
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '网络不佳，请重新进入小程序。',
              complete: (res) => {
              }
            })
            // console.log(err)
            reject(err)
          }
        })
      };
    });
  },

  login: function (callback) {
    wx.login({
      success(res) {
        console.log(res, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")

        if (res.code) { // 发起网络请求
          let data = {
            code: res.code,
            type: 'vend_openid',
          }

          http.post('/auth/checkCode', data).then(res => {
            if (res.code == 200) {
              let token = res.data;
              wx.setStorageSync('access_token', token)
              console.log(wx.getStorageSync('access_token'))
              if (callback) {
                console.log(res, "请求返回")
                callback(res);
              }
            }
          })
        }
      }
    })
  },
  // 版本比对
  compareVersion(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
    return 0
  },
  // 点击授权登录
  onClickLogin: () => {
    let that = this
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        desc: '展示用户信息',
        success: (res) => {
          console.log(res, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
          console.log(res, 'res')
          wx.login({
            success: function (res1) {
              console.log(res1, 'res1')
              wx.showLoading({
                title: '正在登录...',
                icon: 'loading',
              })
              let access_token = wx.getStorageSync('access_token') || ''
              let param = qs.stringify({
                type: 'vend_openid',
                access_token,
                ...res
              })
              // const  SDKVersion  = wx.getSystemInfoSync()
              // let V1 = this.compareVersion(SDKVersion,"2.27.1")
              // console.log(V1)
              http.post('/auth/login', param).then(res4 => {
                if (res4.code == 200) {
                  wx.hideLoading()
                  wx.setStorageSync('userInfo', res4.data)
                  resolve(res4)
                  wx.showToast({
                    title: '登录成功',
                    duration: 2000
                  })
                } else {
                  wx.showModal({
                    title: res4.msg
                  })
                }
              })
              wx.hideLoading({
                success: (res) => { },
              })
            },
          })
        }
      })
    })
  },

  appendParams: function (uri, params) {
    if (uri === '') {
      return '';
    }
    const query = this._formatParams(params);

    if (query !== '') {
      uri += (-1 === uri.indexOf('?')) ? '?' : '&';
      uri += query;
    }
    return uri;
  },
  _formatParams: function (params) {
    let p = [];
    for (const k in params) {
      if (params[k] !== '' && params[k] !== undefined && params[k] !== null) {
        p.push(k + '=' + encodeURIComponent(params[k]).replace(/'/g, ''));
      }
    }
    return p.join('&');
  },

  // 微信调起支付
  wxRquestPayment(data) {
    return new Promise((resolve, reject) => {
      wx.requestPayment({
        'timeStamp': data.timeStamp,
        'nonceStr': data.nonceStr,
        'package': data.package,
        'signType': data.signType,
        'paySign': data.paySign,
        'success': function (res) {
          resolve(res)
        },
        'fail': function (res) {
          // resolve(res)
          reject(res)
        },
        'complete': function (res) {
          resolve(res)
        }
      })
    })
  },

  // 随机字符串
  randomRange: function (min, max) {
    var returnStr = "",
      range = (max ? Math.round(Math.random() * (max - min)) + min : min),
      charStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < range; i++) {
      var index = Math.round(Math.random() * (charStr.length - 1));
      returnStr += charStr.substring(index, index + 1);
    }
    return returnStr;
  },

  // 上传图片
  uploadFile(filePath) {
    return new Promise((resolve) => {
      wx.uploadFile({
        url: this.getUrl('/app/imgUpload'),
        filePath: filePath,
        name: 'file',
        formData: {},
        success: function (res) {
          resolve(JSON.parse(res.data))
        },
        fail(res) {
          resolve(res.data)
        }
      })
    })
  },
  clearStorage() {
    wx.removeStorageSync('access_token')
    wx.removeStorageSync('userInfo')
  }
}

// 导出
module.exports = {
  $http: http,
}